package org.wmine.eventhandlers;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.event.TableModelListener;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//import java.lang.Exception;
import org.wmine.data.*;
//import java.lang.Integer.p

import java.io.IOException;
import java.io.StringBufferInputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class MissingValueEventHandler extends JDialog implements ActionListener,TableModelListener
{
	JTable tableData;
	JScrollPane scrollPane;	
	DefaultTableModel dtm;
	JButton btnMissing;
	JRadioButton radioRemove,radioEdit;
	ButtonGroup bg;
	String dataValues[][];
	String[] columnNames;
	Iterator itrAttr;//=d.getAttributeIterator();
	
	//ArrayList lst=new ArrayList();
	int cntRow,cntCol;
	String tablename;
	
	public MissingValueEventHandler(Frame ownerFrame)
	{
		//this.tablename=tablename;
		super(ownerFrame,true);
		this.setLayout(null);
		this.setBounds(200,160,600,500);
		this.setTitle("Missing Values");
		bg=new ButtonGroup();
		radioRemove=new JRadioButton("Remove Missing Values");
		radioEdit=new JRadioButton("Edit Missing Values");
		radioRemove.addActionListener(this);
		radioEdit.addActionListener(this);
		
		radioRemove.setBounds(50,50,200,25);
		radioEdit.setBounds(300,50,200,25);
		radioRemove.setSelected(true);
		
		this.add(radioRemove);
		this.add(radioEdit);
		
		bg.add(radioRemove);
		bg.add(radioEdit);
		
		// calling function to load data in all respective tables-- table,attribute,tuple..
		try
		{
		LoadData();
		}catch(Exception e){}
		

		// loading data in jtable
		
		dtm=new DefaultTableModel(dataValues,columnNames);
		tableData = new JTable(dtm);
		tableData.setEnabled(false);
		dtm.addTableModelListener(this);
		//tableData.setForeground(Color.black);
	
		
		scrollPane=new JScrollPane(tableData);
		scrollPane.setBounds(20,100,550,300);
		this.add(scrollPane);
	
		btnMissing =new JButton("Remove Missing");
		btnMissing.setBounds(200,420,150,25);
		btnMissing.addActionListener(this);	
		this.add(btnMissing);
		
		this.setVisible(true);
		
		
	}
	void LoadData() throws ParserConfigurationException, SAXException, IOException
	{
		
		DataSet dataSet = new DataSet();
		// "E:\\semester 3\\rajeev\\rajeev\\WMine\\xmldoc02.xml"
		dataSet.setDataReader(new XMLDataReader(new StringBufferInputStream("C:\\xmldoc.xml")));
		
		tablename=dataSet.getTableName();
		System.out.println("data loaded");
		cntCol=dataSet.getAttributeCount();
		cntRow=dataSet.getTupleCount();
		System.out.println(cntCol+ " " +cntRow);
		
		columnNames=new String[cntCol];
		Iterator<Attribute> colnames= dataSet.getAttributeIterator();
		itrAttr=colnames;
		int i=0;
		
		while(colnames.hasNext())
		{
			Attribute s=colnames.next();
			System.out.println("s:"+s.getAttributeName());
			columnNames[i++]=s.getAttributeName();
		}
		
		Table table=new Table();
		String tablename=table.getNameTable();
		System.out.println("tablename: "+tablename);
		TableResultSet resultSet = dataSet.getTableResultSet();
	
		// creating memory for dataValues
		dataValues=new String[cntRow][cntCol];
	 	int j=0;
		while(resultSet.hasNext()) 
		{
			try 
			{
				
				for(i=0;i<cntCol;i++)
				{
					if(resultSet.getString(i).equals("null"))
						dataValues[j][i]="?";
					else
						dataValues[j][i]=resultSet.getString(i);
					System.out.println("Tuple :"+ resultSet.getString(i));
				}
			}catch (InvalidCursorPositionException e) 
			{
				e.printStackTrace();
			}
			j++;
		}
	
		
	}

	/*public static void main(String [] args)
	{
		new MissingValueEventHandler("Project");
	}*/
	
	public void tableChanged(TableModelEvent tme)
	{
		System.out.println("table changed");
		//tableData.setModel(dtm);
		System.out.println(dtm.getDataVector());
		//dtm.newDataAvailable(tme);
		
		
	}
	@SuppressWarnings("deprecation")
	public void actionPerformed(ActionEvent ae)
	{
		
		String str=ae.getActionCommand();
	
		ArrayList lst=new ArrayList();
		
		int flag=0;
		if(str=="Remove Missing")
		{
			
			System.out.println("in rem miss "+dtm.getDataVector()+ "\ncntrow:"+cntRow);
		
			try
			{
				if(dtm.getRowCount()>0)
				{
					for(int i=0;i<cntRow;i++)
					{
						for(int j=0;j<cntCol;j++)
						{
							System.out.println("for j:"+i+" "+j+ " "+dtm.getValueAt(i,j));
							if(dtm.getValueAt(i,j).toString().equals("?") || dtm.getValueAt(i,j).toString().trim().equals(""))
							{	
								
								lst.add(i);
								tableData.setSelectionBackground(Color.red);
								//dtm.
								
								System.out.println("in if: "+i);
						
								flag=1;
							}
						}		
					}
				}
				else
					JOptionPane.showMessageDialog(null,"No data found");	
				
				
				RemoveMissingRows(lst);	
				btnMissing.setLabel("Save Values");
			
			}
			
			catch(Exception e)
			{
				System.out.println(e);
			}
		}
		else if(str=="Save Values")
		{
			
			if(dtm.getRowCount()<=0)
			{
				JOptionPane.showMessageDialog(null,"No data Found!!");	
			}
			else if(ContainsMissingValues())
			{
				JOptionPane.showMessageDialog(null,"There are still missing values...Please fill them...");	
			}
			else
			{
				// write code here to convert data from table to xml
				String filename=JOptionPane.showInputDialog("Enter filename");
				
				if(filename!=null)
				{
					//Table t=new Table();
					//t.getNameTable();
				//ConvertToXML c=new ConvertToXML(dtm,filename,this.tablename);
					org.wmine.core.XmlConvert x=new org.wmine.core.XmlConvert(tablename);
					x.CreateTableXML(filename,cntCol,cntRow,itrAttr,dtm);
					JOptionPane.showMessageDialog(null,"Data Converted to "+filename+".xml");
					
					
				}
			}
		}
		else if(str=="Remove Missing Values") // for radio button-- Remove
		{
			
			btnMissing.setLabel("Remove Missing");
			tableData.setEnabled(false);
			
		}
		
		else if(str=="Edit Missing Values") // for radio button -- Edit
		{
		
			btnMissing.setLabel("Save Values");
			tableData.setEnabled(true);
		}

	}
	
	
	void RemoveMissingRows(ArrayList lst)
	{
		int cnt=0;
		System.out.print("lstsize:"+lst.size());
		if(lst.size()>0)
		{
			int msg=JOptionPane.showConfirmDialog(this,"Are you sure u want to delete all missing records?");
					
			if(msg==0)
			{
				for(int i=0;i<lst.size();i++)
				{
					//String str=;
					dtm.removeRow(Integer.parseInt(lst.get(i).toString())-cnt);
					cnt++;
					cntRow--;
				}
			
				JOptionPane.showMessageDialog(null,""+lst.size()+" missing values found and removed!!");
			}
		}
		else
			JOptionPane.showMessageDialog(null,"No missing values found !!");
		
	}
	
	boolean ContainsMissingValues()
	{
		if(dtm.getRowCount()>0)
		{
			for(int i=0;i<cntRow;i++)
			{
				for(int j=0;j<cntCol;j++)
				{
					if(dtm.getValueAt(i,j).toString()=="")
						return true;
				}
			}
		}
		return false;	
	}
	

}
